package user

import (
	"crypto/md5"
	"fmt"
	"gitee.com/jjj-server/mdb"
	"log"
	"strconv"
	"time"
)

// 用户类型
const(
	NormalUser = 0	// 普通用户 <兼职者>
	JobProvider = 1	// 兼职提供者
	OP = 1000		// 管理员
)

// 错误码
const(
	UserExists = 1000	// 用户存在
	UserNExists = 1001 // 用户不存在
	FToAUser = 1002  // 添加用户失败
	FToUUserP = 1003 // 更新用户档案失败
	SToUUserP = 1015 // 更新用户档案成功
	AddedUser = 1004 // 成功添加用户
	FToDUser = 1005 // 删除用户失败、
	FToDUserB = 1006 // 删除用户失败
	FToDUserP = 1007 // 删除用户档案失败
	DeletedUser = 1008 // 删除用户成功
	FToCPasswd = 1009 // 修改用户密码失败
	SToCPasswd = 1010 // 修改用户密码成功
	FToCheckUExists = 1011 // 无法检测用户存在
	NickExists = 1012	// 昵称存在
	NickNExists = 1013 // 昵称不存在
	FToCheckNExists = 1014 // 无法检测用户存在
	FToGetUID = 1015 // 获取用户UID失败


	UserAdded = 1020 // 用户添加成功
	FToAddU = 1021 // 用户添加失败

)

 type UserProfile struct{
	Uid string `json:"uid"`				// 用户ID
	//UserName string `json:"username"`	// 用户登录名
	//PassWord string `json:"password"` 	// 用户密码
	NickName string `json:"nickname"`	// 昵称
	RealNmae string `json:"realname"`	// 姓名
	Sex int `json:"sex"`				// 性别
	Age int `json:"age"`				// 年龄
	Phone string `json:"phone"`			// 电话号码
	QQ string `json:"qq"`				// QQ  
}

// 生成用户Uid
func GenerateUid(utype int)string{
	tn := strconv.Itoa(int(time.Now().Unix()))
	log.Println("-> Generate user id from unix: ",tn)
	has := md5.Sum([]byte(tn))
	hastr := fmt.Sprintf("%x",has)
	uid := strconv.Itoa(utype) + hastr
	log.Println("<- Generated user id: ",uid)
	return uid
}

// 添加用户
func AddUser(username string,password string,utype int)int{
	if CheckUserExists(username) == UserExists{
		log.Println("<- Failed to add user: ",username," <User Exists>")
		return UserExists
	}
	db := mdb.ConnectDB()
	defer db.Close()
	uid := GenerateUid(utype)
	ret,err :=db.Exec("INSERT INTO users(uid, username, password, role) VALUES(?,?,?,?)",uid,username,password,utype)
	if err != nil{
		log.Println("<- Failed to add user: ",err)
		return FToAUser
	}
	success := UpdateUserProfile(UserProfile{
		Uid: uid,
		NickName: "用户" + uid,
		RealNmae: "",
		Sex:      0,
		Age:      0,
		Phone:    "",
		QQ:       "",
	})
	if success == FToUUserP{
		log.Println("<- Failed to update user profile for new user: ",uid," <",err,">")
		return FToUUserP
	}
	added,_ := ret.RowsAffected()
	log.Println("<- UID: ",uid)
	log.Println("<- Added ",added," Users.")
	return AddedUser
}

// 删除用户	<后期建立删除用户缓冲池>
func DelUser(username string)int{
	db := mdb.ConnectDB()
	defer db.Close()
	log.Println("-> Start to delete user: ",username)
	_,err := db.Exec("DELETE FROM users WHERE username = ?",username)
	if err != nil{
		log.Println("-> Failed to delete user base: ",err)
		return FToDUserB
	}
	row := db.QueryRow("SELECT uid FROM users WHERE username = ?",username)
	var uid string
	row.Scan(&uid)
	_,err = db.Exec("DELETE  FROM user_profile WHERE uid = ?",uid)
	if err != nil{
		log.Println("-> Failed to delete user profile: ",err)
		return FToDUserP
	}
	log.Println("<- USER DELETED SUCCESSFULLY")
	return DeletedUser
}

// 修改密码
func ChangeUserPasswd(username string,password string)int{
	db := mdb.ConnectDB()
	defer db.Close()
	_,err := db.Exec("UPDATE users SET  password = ? WHERE username = ?",password,username)
	if err != nil{
		log.Println("<- Failed to change password for user: ",err)
		return FToCPasswd
	}
	return SToCPasswd
}


// 检测用户是否存在
func CheckUserExists(username string) int{
	db := mdb.ConnectDB()
	defer db.Close()
	rows,err  := db.Query("SELECT uid FROM users WHERE username = ?",username)
	if err != nil{
		log.Println("<- Failed to check user exists: ",err)
		return FToCheckUExists
	}
	var count int
	for rows.Next(){
		count += 1
	}
	if count != 0{
		return UserExists  	// 用户不存在<可注册>
	}
	return UserNExists		// 用户已存在<不可注册>
}

// 检测用户昵称是否被使用
func CheckNickNameExists(nickname string) int{
	db := mdb.ConnectDB()
	defer db.Close()
	rows,err  := db.Query("SELECT uid FROM user_profile WHERE nickname = ?",nickname)
	if err != nil{
		log.Println("<- Failed to check nickname exists: ",err)
		return FToCheckNExists
	}
	var count int
	for rows.Next(){
		count += 1
	}
	if count != 0{
		return NickNExists	// 用户昵称不存在<可使用>
	}
	return NickExists			// 用户昵称已存在<不可使用>
}


// 编辑用户
// 个人信息
// uid: 用户id	nickname: 昵称	realname: 真实姓名	sex: 性别<0/1|男/女>		age: 年龄<int>	phone: 手机号<string>	qq:<string>
func UpdateUserProfile(profile UserProfile)int{
	db := mdb.ConnectDB()
	defer db.Close()
	ins,err := db.Exec("UPDATE user_profile SET nickname,realname,sex,age,phone,qq = ?,?,?,?,?,?",profile.NickName,profile.RealNmae,profile.Sex,profile.Age,profile.Phone,profile.QQ)
	if err != nil{
		log.Println("<- Failed to update user profile: ",err,"\n Try insert user profile: ")
		_,err := db.Exec("INSERT INTO  user_profile(uid,nickname,realname,sex,age,phone,qq) VALUES(?,?,?,?,?,?,?)",profile.Uid,profile.NickName,profile.RealNmae,profile.Sex,profile.Age,profile.Phone,profile.QQ)
		if err != nil{
			log.Println("<- Failed to insert user profile: ",err)
			return FToAddU
		}
		return SToUUserP
	}
	ls,_ := ins.LastInsertId()
	log.Println("<- Inserted 1 user id: ",ls)
	return SToUUserP
}

// 修改昵称
func UpdateUserNickName(nickname string)int{
	if CheckNickNameExists(nickname) == NickExists{
		log.Println("Nickname Exists")
		return 1
	}
	db := mdb.ConnectDB()
	defer db.Close()
	_,err := db.Exec("UPDATE user_profile SET nickname = ?",nickname)
	if err != nil{
		log.Println("<- Failed to change usernick: ",err)
		return FToUUserP
	}
		log.Println("<- Updated User NickName")
	return SToUUserP
}

// 修改姓名
func UpdateUserRealName(realname string)int{
	db := mdb.ConnectDB()
	defer db.Close()
	_,err := db.Exec("UPDATE user_profile SET realname = ?",realname)
	if err != nil{
		log.Println("<- Failed to change Realname: ",err)
		return FToUUserP
	}
	log.Println("<- Updated User Realname")
	return SToUUserP
}

// 修改性别
func UpdateUserSex(sex int)int{
	db := mdb.ConnectDB()
	defer db.Close()
	_,err := db.Exec("UPDATE user_profile SET sex = ?",sex)
	if err != nil{
		log.Println("<- Failed to change sex: ",err)
		return FToUUserP
	}
	log.Println("<- Updated User Sex")
	return SToUUserP
}

// 修改年龄
func UpdateUserAge(age int)int{
	db := mdb.ConnectDB()
	defer db.Close()
	_,err := db.Exec("UPDATE user_profile SET age = ?",age)
	if err != nil{
		log.Println("<- Failed to change age: ",err)
		return FToUUserP
	}
	log.Println("<- Updated User Age")
	return SToUUserP
}

// 修改手机号
func UpdateUserPhone(phone string)int{
	db := mdb.ConnectDB()
	defer db.Close()
	_,err := db.Exec("UPDATE user_profile SET phone = ?",phone)
	if err != nil{
		log.Println("<- Failed to change phone: ",err)
		return FToUUserP
	}
	log.Println("<- Updated User Phone")
	return SToUUserP
}

// 修改QQ
func UpdateUserQQ(qq string)int{
	db := mdb.ConnectDB()
	defer db.Close()
	_,err := db.Exec("UPDATE user_profile SET qq = ?",qq)
	if err != nil{
		log.Println("<- Failed to change qq: ",err)
		return FToUUserP
	}
	log.Println("<- Updated User QQ")
	return SToUUserP
}

// 获取用户ID
func GetUserId(username string)string{
	db := mdb.ConnectDB()
	defer db.Close()
	ret := db.QueryRow("SELECT uid FROM users WHERE username = ?",username)
	var uid string
	err := ret.Scan(&uid)
	if err != nil{
		log.Println("<- Failed to get user uid: ",err)
		return string(FToGetUID)
	}
	return uid
}
